package com.siemens.industrial.web.mvc.controller.partner.user;

import com.siemens.industrial.model.admin.SystemConfig;
import com.siemens.industrial.model.partner.Metadata;
import com.siemens.industrial.model.partner.User;
import com.siemens.industrial.utils.*;
import com.siemens.industrial.utils.GlobalResponseCode;
import com.siemens.industrial.utils.JsonToOtherFormat;
import com.siemens.industrial.utils.RestResponse;
import com.siemens.industrial.utils.SiemensException;
import com.siemens.industrial.web.mvc.pojo.DataTableQuery;
import com.siemens.industrial.web.mvc.service.AuthService;
import com.siemens.industrial.web.mvc.service.WriteLogs;
import com.siemens.industrial.web.mvc.service.admin.TenantService;
import com.siemens.industrial.web.mvc.service.partner.PartnerMetadataService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by qupen on 2016/10/10.
 */
@Controller
public class PartnerMetadataController {

    @Resource
    PartnerMetadataService partnerMetadataService;

    @Resource
    TenantService tenantService;

    @Resource
    WriteLogs writeLogs;

    @Resource
    AuthService authService;

    @RequestMapping(value = "/partner/{tenant}/metadata/list", method = RequestMethod.GET)
    public String getPage(@PathVariable("tenant") String tenantKey, ModelMap modelMap) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        modelMap.put("key", tenantKey);
        return "partner/user/machineMetadata_manage";
    }

    @RequestMapping(value = "/partner/{tenant}/api/v1/metadata/addIDLE", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> createMetadataIDLE(@PathVariable("tenant") String tenantKey, @RequestBody ArrayList<Map<String, Object>> metadatas) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        partnerMetadataService.batchSave(tenantId, metadatas, "IDLE");

        return RestResponse.create(GlobalResponseCode.SUCCESS).build();
    }

    @RequestMapping(value = "/partner/{tenant}/api/v1/metadata/addFaultType", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> createMetadataFaultType(@PathVariable("tenant") String tenantKey, @RequestBody ArrayList<Map<String, Object>> metadatas) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        partnerMetadataService.batchSave(tenantId, metadatas, "FaultType");

        return RestResponse.create(GlobalResponseCode.SUCCESS).build();
    }

    @RequestMapping(value = "/partner/{tenant}/api/v1/metadata/MachineNumber", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> createMetadataMachineNumber(@PathVariable("tenant") String tenantKey, @RequestBody ArrayList<Map<String, Object>> metadatas) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        partnerMetadataService.batchSaveMT(tenantId, metadatas, "MachineNumber");

        return RestResponse.create(GlobalResponseCode.SUCCESS).build();
    }

    @RequestMapping(value = "/partner/{tenant}/api/v1/metadata/metadatas", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getMetadatasByKey(@PathVariable("tenant") String tenantKey, String key) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        List<Metadata> metadataList = partnerMetadataService.getAllByKey(tenantId, key);

        return RestResponse.create(GlobalResponseCode.SUCCESS).putData(metadataList).build();
    }

    @RequestMapping(value = "/partner/{tenant}/api/v1/metadata/metadataList", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getMetadatas(@PathVariable("tenant") String tenantKey) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        List<Metadata> metadataList = partnerMetadataService.getMetadataList(tenantId);

        return RestResponse.create(GlobalResponseCode.SUCCESS).putData(metadataList).build();
    }

    @RequestMapping(value = "/partner/{tenant}/api/v1/metadata/delete", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> deleteMetadata(@PathVariable("tenant") String tenantKey, @RequestParam(name = "metadataId") String metadataId) throws SiemensException {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        Metadata metadata = partnerMetadataService.getMetadata(tenantId, metadataId);
        String value = metadata.getMetaDefinition();
        partnerMetadataService.deleteMetadata(tenantId, metadataId);
        Map<String, Object> map = JsonToOtherFormat.buildJsonToMap(value);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        User currentUser = (User) authService.currentUser();
        String reason = "";
        if (map.containsKey("IDLEReason")) {
            reason = map.get("IDLEReason").toString();
        } else if (map.containsKey("MachineType")) {
            reason = map.get("MachineType").toString();
        } else if (map.containsKey("FaultTypeReason")) {
            reason = map.get("FaultTypeReason").toString();
        }
        String content = currentUser.getUserName() + "于" + simpleDateFormat.format(new Date()) + "删除了元数据" + "\"" + reason + "\"。";
        writeLogs.writeLog(SystemConfig.LOG_USER_OPERATE_KEY, content, tenantKey + "_operate");
        return RestResponse.create(GlobalResponseCode.SUCCESS).build();
    }

    @RequestMapping(value = "/partner/{tenant}/api/v1/metadata/getSetting", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getSetting(@PathVariable("tenant") String tenantKey) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        Map<String, Object> map = partnerMetadataService.getSetting(tenantId);
        return RestResponse.create(GlobalResponseCode.SUCCESS).putData(map).build();
    }

    @RequestMapping(value = "/partner/{tenant}/api/v1/metadata/updateSetting", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> updateSetting(@PathVariable("tenant") String tenantKey, @RequestParam(name = "value") String value) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        partnerMetadataService.setAvailability(tenantId, value);
        return RestResponse.create(GlobalResponseCode.SUCCESS).build();
    }

    @RequestMapping(value = "/partner/{tenant}/api/v1/metadata/init", method = RequestMethod.GET)
    public String metadataInit(@PathVariable("tenant") String tenantKey) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();

        return "partner/user/machineMetadata_init";
    }

    @RequestMapping(value = "/partner/{tenant}/state/settingList", method = RequestMethod.GET)
    public String settings(@PathVariable("tenant") String tenantKey, ModelMap modelMap) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        modelMap.put("status", Definition.STATUSTYPE.getData());
        return "partner/user/state_setting_list";
    }

    @RequestMapping(value = "/partner/{tenant}/state/stateSetting", method = RequestMethod.GET)
    public String stateSetting(@PathVariable("tenant") String tenantKey) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();

        return "partner/user/state_new_settings";
    }

    @RequestMapping(value = "/partner/{tenant}/api/v1/state/stateSetting", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> saveStateSetting(@PathVariable("tenant") String tenantKey, @RequestBody Map<String, Object> data) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();

        partnerMetadataService.saveStateSettings(data, tenantId);
        return RestResponse.create(GlobalResponseCode.SUCCESS).build();
    }

    @RequestMapping(value = "/partner/{tenant}/api/v1/state/getAllSetting", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getStateSettings(@PathVariable("tenant") String tenantKey) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();

        List<Map<String, Object>> list = partnerMetadataService.getAllSettings(tenantId);
        return RestResponse.create(GlobalResponseCode.SUCCESS).putData(list).build();
    }

    @RequestMapping(value = "/partner/{tenant}/api/v1/state/save", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> getStateSettings(@PathVariable("tenant") String tenantKey, @RequestParam(name = "ids") String ids) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        partnerMetadataService.saveStatusTypes(tenantId, ids);
        return RestResponse.create(GlobalResponseCode.SUCCESS).build();
    }

    @RequestMapping(value = "/partner/{tenant}/api/v1/state/get", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getStates(@PathVariable("tenant") String tenantKey) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        Metadata m = partnerMetadataService.getStatus(tenantId, "statustype");
        return RestResponse.create(GlobalResponseCode.SUCCESS).putData(m).build();
    }

    @RequestMapping(value = "/partner/{tenant}/api/v1/metadata/getOne", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getOneById(@PathVariable("tenant") String tenantKey, String metaId) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        Metadata m = partnerMetadataService.getMetadata(tenantId, metaId);
        return RestResponse.create(GlobalResponseCode.SUCCESS).putData(m).build();
    }

    @RequestMapping(value = "/partner/{tenant}/api/v1/metadata/updateByMetaId", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> getOneById(@PathVariable("tenant") String tenantKey,
                                          @RequestBody Map<String, Object> map) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        partnerMetadataService.updateById(tenantId, map.get("definition"), map.get("metaId").toString());
        return RestResponse.create(GlobalResponseCode.SUCCESS).build();
    }

    @RequestMapping(value = "/partner/{tenant}/api/v1/state/getAllSettingByDataTable", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getStateSettingsByDataTable(@PathVariable("tenant") String tenantKey,
                                                           HttpServletRequest request) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();

        DataTableQuery dt = new DataTableQuery(request);

        if (dt.isDataTableRequest()) {
            Map<String, Object> status = partnerMetadataService.getAllSettingsByDataTable(tenantId, request);
            return status;
        }

        return dt.buildResponse(0, 0, new ArrayList<>());
    }

    @RequestMapping(value = "/partner/{tenant}/api/v1/state/getOldSetting", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getStateSettingsByTypeId(@PathVariable("tenant") String tenantKey,
                                                        String type, String stType) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        Map<String,Object> map = partnerMetadataService.getValueByStType(tenantId, type, stType);
        return RestResponse.create(GlobalResponseCode.SUCCESS).putData(map).build();
    }

    //get Value(status type) by deviceType
    @RequestMapping(value = "/partner/{tenant}/api/v1/stateTypeByDeviceType", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> stateTypeByDeviceType(@PathVariable("tenant") String tenantKey,
                                                        String type) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        Map<String,Object> map = new HashMap<>();
        List<Map<String,Object>> typeValues = partnerMetadataService.getValueByDeviceType(tenantId, type);
        List statusTypeList = new ArrayList<>();
        if(typeValues != null){
            for (Map<String, Object> typeInfo:typeValues){
                statusTypeList.add(Definition.STATUSTYPE.getData(Integer.parseInt(typeInfo.get("stType").toString())));
            }
        }
        map.put("typeValues",typeValues);
        map.put("statusTypeList",statusTypeList);
        return RestResponse.create(GlobalResponseCode.SUCCESS).putData(map).build();
    }
}
